package com.zhouyilin.bigevent2.interceptions;

import com.zhouyilin.bigevent2.pojo.Result;
import com.zhouyilin.bigevent2.utils.JwtUtil;
import com.zhouyilin.bigevent2.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.ErrorResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LogginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        令牌验证
        String token = request.getHeader("Authorization");
        try {

//            从redis中获取token
            ValueOperations<String,String> ops = stringRedisTemplate.opsForValue();
            String redisToken = ops.get(token);

            if (redisToken == null) {
                throw new RuntimeException();
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);
//            把业务数据存放在ThreadLocal中
            ThreadLocalUtil.set(claims);
//            放行
            return true;
        } catch (Exception e) {
//            设置状态为401
            response.setStatus(401);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        清空ThreadLocal中的数据，防止内存泄露
        ThreadLocalUtil.remove();
    }
}
